<?php
/**
 * JWT认证中间件
 */

namespace app\middleware;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\facade\Request;
use think\facade\Config;

class JwtAuth
{
    private $jwtKey;

    public function __construct()
    {
        // 从配置文件中读取JWT密钥
        $this->jwtKey = Config::get('jwt.key', 'GOUGUOA');
    }

    public function handle($request, \Closure $next)
    {
        \think\facade\Log::info('JwtAuth中间件被调用', [
            'pathinfo' => $request->pathinfo(),
            'method' => $request->method()
        ]);

        // 排除不需要认证的路由
        $excludeRoutes = [
            'api/auth/login',
            'api/auth/login/',
            'api/auth/register',
            'api/auth/userInfo',
            'auth/login',
            'auth/register',
            'captcha',
            'captcha/',
            'api/captcha',
            'api/captcha/',
            'api/cors/test',
            'api/cors/debug',
            'index',
            'index/index',
            'index/hello',
            'index/dbtest',
            'dbtest',
            'dbtest/tables',
            'dbtest/users',
            'dbtest/test',
            'api/database-test/connection',
            'api/database-test/table-structure',
            'api/database-test/permission-tables',
            'home/login/submit',
            'home/login/index',
            'home/login',
            'api/home/files/upload',
            'home/files/upload',
            'api/system/region',
            'api/home/area',
            'api/disk/download-attachment',
            'api/file/download',
            'file/download',
            'home/files/download',
            'home/files/batch_download',
            'api/customer/basic/set',
            'api/customer/basic/list'
        ];
        $currentRoute = $request->pathinfo();

        // 调试信息：记录当前请求的路由
        \think\facade\Log::record("当前请求路由: " . $currentRoute, 'debug');

        // 检查是否匹配排除路由（支持部分匹配）
        foreach ($excludeRoutes as $excludeRoute) {
            if (strpos($currentRoute, $excludeRoute) !== false || $currentRoute === $excludeRoute) {
                \think\facade\Log::record("路由匹配排除规则: " . $excludeRoute, 'debug');
                return $next($request);
            }
        }

        // 特殊处理：确保登录路由被正确排除
        if ($currentRoute === 'api/auth/login' || $currentRoute === 'api/auth/login/') {
            return $next($request);
        }

        // 获取token - 优先从URL参数获取
        $token = $request->param('token');
        if (!$token) {
            // 如果URL参数中没有token，则从Authorization头获取
            $token = $request->header('Authorization');
            if (!$token) {
                return json(['code' => 401, 'msg' => '未授权']);
            }
        }

        // 移除Bearer前缀（如果存在）
        $token = str_replace('Bearer ', '', $token);

        try {
            $decoded = JWT::decode($token, new Key($this->jwtKey, 'HS256'));
            $userId = $decoded->sub;

            \think\facade\Log::info('尝试查询用户信息', ['userId' => $userId]);

            // 从数据库获取完整的用户信息（使用oa_admin表）
            $user = \think\facade\Db::name('admin')
                ->where('id', $userId)
                ->where('status', 1)
                ->find();

            if (!$user) {
                \think\facade\Log::error('用户不存在或已禁用', ['userId' => $userId]);
                return json(['code' => 401, 'msg' => '用户不存在或已禁用']);
            }

            \think\facade\Log::info('用户数据字段', [
                'userId' => $userId,
                'user_fields' => array_keys($user),
                'user_data' => $user
            ]);

            // 获取用户角色信息（使用oa_admin_group表）
            $groupId = $user['group_id'] ?? null;
            if (!$groupId) {
                \think\facade\Log::error('用户角色ID不存在', ['userId' => $userId, 'user_fields' => array_keys($user)]);
                return json(['code' => 401, 'msg' => '用户角色配置错误']);
            }

            $group = \think\facade\Db::name('admin_group')
                ->where('id', $groupId)
                ->find();

            // 组织用户信息
            $userInfo = [
                'id' => $user['id'] ?? 0,
                'username' => $user['username'] ?? '',
                'nickname' => $user['nickname'] ?? '',
                'email' => $user['email'] ?? '',
                'mobile' => $user['mobile'] ?? '',
                'avatar' => $user['thumb'] ?? '',
                'gid' => $groupId,
                'group' => $group,
                'did' => $user['did'] ?? 0,
                'pid' => $user['position_id'] ?? 0,
                'status' => $user['status'] ?? 0,
                'login_time' => $user['last_login_time'] ?? 0,
                'login_ip' => $user['last_login_ip'] ?? '',
                'rules' => $group['rules'] ?? '',
            ];

            // 将用户信息附加到请求对象
            $request->userId = $userId;
            $request->userInfo = $userInfo;

            return $next($request);
        } catch (\Exception $e) {
            \think\facade\Log::error('JWT解析失败', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'token' => $token // 记录token用于调试
            ]);
            return json(['code' => 401, 'msg' => '令牌无效或已过期: ' . $e->getMessage()]);
        }
    }
}
